<template>
  <div class="materials-manage-container item-manage-container">
    <div class="item-manage-container-right">
      <div class="page-header">
        <div class="page-header-title">
          材料管理
          <span v-for="item in operList" :key="item.id">{{ item.name }}</span>
        </div>
        <div class="page-header-button flex-center">
          <el-button :type="showType === 'icon' ? 'primary' : ''" @click="changeShowType('icon')">
            <div class="flex-center">
              <i class="iconfont icon-tubiao"></i>
              图标展示
            </div>
          </el-button>
          <el-button :type="showType === 'table' ? 'primary' : ''" @click="changeShowType('table')">
            <div class="flex-center">
              <i class="iconfont icon-table"></i>
              列表展示
            </div>
          </el-button>
        </div>
      </div>
      <div class="context search-container">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-row>
            <el-col :span="24">
              <el-form-item style="margin-right: 60px" label="材料名称：">
                <el-input v-model="formInline.materialName" placeholder="请输入材料名称" clearable></el-input>
              </el-form-item>
              <el-form-item style="margin-right: 60px" label="应用范围：">
                <el-radio-group v-model="formInline.scope">
                  <el-radio label="" border>全部</el-radio>
                  <el-radio label="0" border>公共材料</el-radio>
                  <el-radio label="1" border>部门材料</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="margin-right: 60px" v-if="formInline.scope == 1" label="选择部门">
                <cascaderDepart @selectChange="handleDepIdChange" />
              </el-form-item>
              <el-form-item style="float: right">
                <el-button type="primary" @click="onSearch('click')" style="width: 120px">搜索</el-button>
                <el-button type="primary" @click="addItem" style="width: 120px">新建</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-show="showType === 'table'" v-loading="loading" class="tableBox">
        <el-table
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="100%"
          @selection-change="handleSelectionChange"
          @row-contextmenu="openContextMenu"
        >
          <el-table-column type="selection" align="center" width="60"></el-table-column>
          <el-table-column prop="materialName" label="材料名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="materialTypeName" show-overflow-tooltip label="材料类型"></el-table-column>
          <el-table-column prop="fromName" show-overflow-tooltip label="材料形式"></el-table-column>
          <el-table-column prop="necessityName" show-overflow-tooltip label="材料必要性"></el-table-column>
          <el-table-column prop="necessityName" show-overflow-tooltip label="应用范围">
            <template slot-scope="scope">
              {{ scope.row.scope == '0' ? '公共材料' : '部门材料' }}
            </template>
          </el-table-column>
          <el-table-column prop="deptName" show-overflow-tooltip label="归属部门"></el-table-column>
          <el-table-column prop="deptName" show-overflow-tooltip label="状态">
            <template slot-scope="scope">
              {{ scope.row.state == 'Y' ? '有效' : '失效' }}
            </template>
          </el-table-column>
          <el-table-column prop="stateDate" show-overflow-tooltip label="状态变更时间"></el-table-column>
          <el-table-column prop="userName" show-overflow-tooltip label="操作人"></el-table-column>
          <el-table-column prop="channelName" show-overflow-tooltip label="来源渠道"></el-table-column>
          <!-- <el-table-column label="操作" width="160">
            <template slot-scope="scope">
              <el-button type="text" size="small" slot="reference" @click="preview(scope.row)">预览</el-button>
              <el-button type="text" size="small" slot="reference" @click="editTableHandle(scope.row)">编辑</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div
        v-show="showType === 'icon'"
        v-loading="loading"
        class="iconBox"
        @contextmenu="openContextMenu(null, '', $event)"
      >
        <el-checkbox-group v-if="tableData.length" v-model="checkBoxGroup" size="small">
          <div class="checkbox-group-container none-checkbox">
            <el-checkbox
              v-for="item in tableData"
              :key="item.thingId"
              :label="item"
              @contextmenu.prevent.native="openContextMenu(item, '', $event)"
            >
              <span class="checkbox-group-container-item">
                <img class="checkbox-img" src="img/itemManage/materials.png" />
                <div class="checkbox-label">{{ item.materialName }}</div>
              </span>
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <div v-else class="none-data">
          <span>暂无数据</span>
        </div>
      </div>
      <div class="fenye">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <ul v-show="contextmenuVisible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li v-show="!selectItem" @click="addItem">新建</li>
      <span v-show="selectItem">
        <li @click="editItem">编辑</li>
        <li @click="showItem">查看</li>
        <li @click="takeEffect">生效</li>
        <li @click="loseEffect">失效</li>
        <li @click="preview">预览</li>
        <li @click="deleteHandle">删除</li>
        <!-- <li @click="showMIndMap">查看脑图</li> -->
      </span>
    </ul>
    <add
      :materialType="materialType"
      :materialForm="materialForm"
      :materialSourceChannel="materialSourceChannel"
      :materialWhether="materialWhether"
      :visible.sync="visible.add"
      :action="selectItem"
      :handleType="handleType"
      @addSuccess="fetchDataList"
    />
  </div>
</template>

<script>
  import axios from 'axios';
  import add from './components/add';
  import { getAreaDepartTree } from '@/api/itemManage';
  import { queryDict } from '@/api/common';
  import cascaderDepart from '../../components/dynamicForm/cascaderDepart.vue';

  export default {
    components: {
      add,
      cascaderDepart
    },
    data() {
      return {
        operList: [], //正在处理数组
        tableData: [],
        formInline: {
          areaCode: '',
          basicCoding: '', //基本编码
          materialName: '',
          state: '',
          pageSize: 20,
          pageNum: 1,
          scope: '',
          deptId: ''
        },
        total: 0,
        isShowTree: false, //是否显示目录树
        contextmenuVisible: false, //是否显示右键菜单
        left: 0,
        top: 0,
        currentPage: 1,
        treeData: [],
        defaultExpandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'value'
        },
        checkBoxGroup: [], //批量选中数组
        showType: 'icon',
        selectItem: null,
        visible: {
          add: false
        },
        areaMap: {},
        materialType: [],
        materialForm: [],
        materialSourceChannel: [],
        materialWhether: [],
        loading: false,
        handleType: ''
      };
    },
    watch: {
      contextmenuVisible(value) {
        if (value) {
          document.body.addEventListener('click', this.closeContextMenu);
        } else {
          document.body.removeEventListener('click', this.closeContextMenu);
        }
      }
    },
    mounted() {
      this.getAreaDepartTree(); //获取区域信息
      this.init(); //获取值表
    },
    methods: {
      async init() {
        this.loading = true;
        const [res1, res2, res3, res4, res5] = await axios.all([
          this.getMaterialType(),
          this.getMaterialForm(),
          this.getMaterialSourceChannel(),
          this.getWhether()
        ]);
        this.loading = false;
        const { data: data1 } = res1;
        const { data: data2 } = res2;
        const { data: data3 } = res3;
        const { data: data4 } = res4;
        if (data1.success && data2.success && data3.success && data4.success) {
          this.materialType = data1.result || [];
          this.materialForm = data2.result || [];
          this.materialSourceChannel = data3.result || [];
          this.materialWhether = data4.result || [];
          this.fetchDataList();
        }
      },
      setNames() {
        const list = JSON.parse(JSON.stringify(this.tableData)) || [];
        list.forEach((i) => {
          let item;
          item = this.materialType.find((j) => {
            return j.item_value == i.materialTypeId;
          });

          i.materialTypeName = item ? item.item_text : '';

          item = this.materialWhether.find((j) => {
            return j.item_value == i.necessity;
          });
          i.necessityName = item ? item.item_text : '';

          item = this.materialForm.find((j) => {
            return j.item_value == i.fromId;
          });
          i.fromName = item ? item.item_text : '';

          item = this.materialSourceChannel.find((j) => {
            return j.item_value == i.channelId;
          });
          i.channelName = item ? item.item_text : '';
        });
        this.tableData = list;
      },
      // 获取材料类型字典
      getMaterialType() {
        return queryDict({ dict: 'material_type' });
      },
      // 获取材料形式
      getMaterialForm() {
        return queryDict({ dict: 'material_form' });
      },
      // 获取来源渠道
      getMaterialSourceChannel() {
        return queryDict({ dict: 'source_channel' });
      },
      // 获取事项材料是否必须
      getWhether() {
        return queryDict({ dict: 'whether' });
      },
      getTableData() {
        const { scope } = this.formInline;
        let params = {
          scope: this.formInline.scope,
          name: this.formInline.materialName,
          current: this.formInline.pageNum,
          size: this.formInline.pageSize
        };
        if (scope == '1') {
          params.departId = this.formInline.deptId;
        }
        return axios.request({
          url: `/api/v1/event/material/common/page`,
          method: 'get',
          params
        });
      },
      onSearch(type) {
        this.operList = this.operList.length ? [this.operList[0]] : [];
        if (type === 'click') {
          this.formInline.pageNum = 1;
        }
        this.loading = true;
        this.fetchDataList();
      },
      // 获取表单列表
      async fetchDataList() {
        // this.formInline.areaCode = '';
        const { data } = await this.getTableData();
        this.loading = false;
        if (data.success) {
          const { current, size, total, records } = data.result || {};
          this.tableData = records;
          this.formInline.pageNum = current;
          this.formInline.pageSize = size;
          this.total = total;
          this.setNames();
        }
      },
      onSubmit() {
        console.log('submit!');
      },
      nodeClick(node) {
        this.formInline.areaCode = node.key;
        this.operList = [
          {
            id: node.key,
            name: node.value
          }
        ];
        this.onSearch();
      },
      handleSizeChange(val) {
        this.formInline.pageSize = val;
        this.formInline.pageNum = 1;
        this.onSearch();
      },
      handleCurrentChange(val) {
        this.formInline.pageNum = val;
        this.onSearch();
      },
      handleSelectionChange(val) {
        this.checkBoxGroup = val;
      },
      handleMenu() {
        this.isShowTree = !this.isShowTree;
      },
      changeShowType(type) {
        if (this.showType === type) return;
        else {
          this.showType = type;
          //清空多选项
          this.checkBoxGroup = [];
        }
      },
      closeContextMenu() {
        this.contextmenuVisible = false;
      },
      openContextMenu(item, column, e) {
        e.stopPropagation();
        e.preventDefault();
        const menuMinWidth = 105;
        const menuMinHieght = item ? 100 : 30;
        const offsetLeft = this.$el.getBoundingClientRect().left; // container margin left
        const offsetWidth = this.$el.offsetWidth; // container width
        const offsetHeight = this.$el.offsetHeight; // container width
        const maxLeft = offsetWidth - menuMinWidth; // left boundary
        const maxTop = offsetHeight - menuMinHieght; // left boundary
        const left = e.clientX - offsetLeft + 15; // 15: margin right
        const top = e.clientY - 90;
        console.log(maxTop, e.clientY - 90);
        this.left = left > maxLeft ? maxLeft : left;
        // 400
        this.top = top > maxTop ? maxTop : top;
        this.contextmenuVisible = true;
        console.log('右键选中的item---', item);
        this.selectItem = item; //右键选中的item
      },
      //获取区域信息
      async getAreaDepartTree() {
        // 5的树就只有自己的区划和自己的部门。4的树有自己的区划及下级区划及对应的各级部门
        let areaCode = '510000000000';
        const { data } = await getAreaDepartTree(areaCode, true);
        if (data.code === 200) {
          this.treeData = [data.result];
          let firstNode = this.treeData && this.treeData[0];
          this.defaultExpandedKeys = [firstNode.key];
          this.formInline.areaCode = firstNode.key;
          this.areaMap = this.transformAreaMap(this.treeData);
          this.operList = [
            {
              id: firstNode.key,
              name: firstNode.value
            }
          ];
        }
      },
      transformAreaMap(treeData) {
        const tempMap = {};
        function transform(data) {
          data.forEach((e) => {
            tempMap[e.key] = e.value;
            if (e.children && e.children.length) {
              transform(e.children);
            }
          });
        }
        transform(treeData);
        return tempMap;
      },
      //新建
      addItem() {
        this.selectItem = null;
        this.visible.add = true;
        this.handleType = 'edit';
      },
      //编辑
      editItem() {
        this.visible.add = true;
        this.handleType = 'edit';
      },
      // 表格编辑
      editTableHandle(item) {
        this.selectItem = item;
        this.visible.add = true;
      },
      handleDepIdChange(val) {
        this.formInline.deptId = val.value;
      },
      async preview() {
        const { fileName, filePath, newName } = JSON.parse(this.selectItem.sampleTableUrl)[0];
        const params = {
          fileName,
          filePath,
          newName
        };
        const { data } = await axios.request({
          url: '/api/v1/file/ftp/preview',
          method: 'get',
          params
        });
        if (data.success) {
          window.open(data.result);
        }
      },
      async deleteHandle() {
        const { data } = await axios.request({
          url: `/api/v1/event/material/${this.selectItem.materialId}`,
          method: 'delete'
        });
        data.code === 200 && this.$message.success('删除成功！');
        this.onSearch('click');
      },
      //查看
      showItem() {
        this.visible.add = true;
        this.handleType = 'scan';
      },
      //生效
      async takeEffect() {
        const { data } = await axios.request({
          url: `/api/v1/event/material/${this.selectItem.materialId}/state/yx`,
          method: 'get'
        });
        data.code === 200 && this.$message.success('生效成功！');
        this.onSearch('click');
      },
      //失效
      async loseEffect() {
        const { data } = await axios.request({
          url: `/api/v1/event/material/${this.selectItem.materialId}/state/sx`,
          method: 'get'
        });
        data.code === 200 && this.$message.success('失效成功！');
        this.onSearch('click');
      },
      //查看脑图
      showMIndMap() {},
      openAddThing() {
        this.$refs.addOneThing.showDialog = true;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .fenye {
    margin: 20px 0;
    text-align: center;
  }
  .iconBox {
    height: inherit;
    flex: 1;
  }
</style>
